<template>
    <div class="search">

        <div class="search-container">
            <!-- 输入框 + 查询按钮 -->
            <el-input v-model="searchForm.roleName" placeholder="角色名称" clearable
                style="width: 300px; margin-right: 10px;" />
            <el-button type="primary" @click="searchRole">查询</el-button>

            <!-- 复选框 + 职员管理链接 -->
            <el-checkbox v-model="searchForm.status" @change="handleCheck"
                style="margin-left: 20px;">显示禁用职员</el-checkbox>

            <!-- 操作按钮组 -->
            <div class="search-right">
                <el-button type="primary" @click="openAddDialog">新增角色</el-button>
                <el-button type="success" @click="batchOpen">启用</el-button>
                <el-button type="warning" @click="batchClose">禁用</el-button>
                <el-button type="danger" @click="batchDelete">删除</el-button>
                <el-button plain @click="refresh">刷新</el-button>
            </div>
        </div>


        <el-dialog v-model="dialogFormVisible" :title="dialogType === 'add' ? '新增角色' : '编辑角色'" width="500">
            <el-form :model="form">
                <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
                    <el-input v-model="form.roleName" autocomplete="off" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitRole">
                        确认
                    </el-button>
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <el-table :data="rolesData" border style="width: 100%" stripe @selection-change="handleSelection"
        v-loading="tableLoad">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="status" label="状态">
            <template #default="{ row }">
                <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
                    @change="() => handleStatus(row)" />
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button class="!ml-0" icon="Edit" size="small" type="primary" @click="updateRole(scope.row.id)" />
                <el-button type="primary" icon="Delete" size="small" @click="deleteRole(scope.row.id)" />
                <el-button plain icon="Setting" @click="openPermissionDialog(scope.row.id)">分配权限</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="permissionDialogFormVisible" title="权限配置" width="500">
        <el-form :model="form">
            <el-form-item label="权限分配" :label-width="formLabelWidth">
                <el-select v-model="permissionIds" multiple placeholder="请选择" size="small" style="width: 100%">
                    <el-option v-for="item in permissionsData" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitPermissions">确认分配</el-button>
                <el-button @click="permissionDialogFormVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="demo-pagination-block" style="float: right;">
        <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const dialogFormVisible = ref(false)
const permissionDialogFormVisible = ref(false)
const dialogType = ref('add')
const formLabelWidth = '100px'
const tableLoad = ref(false)
const permissionIds = ref([])
const currentRoleId = ref(null)

// 搜索表单
const searchForm = reactive({
    roleName: '',
    status: 1,
})

// 添加表单
const form = ref({
    roleName: '',
    status: '',
})


const pageInfo = reactive({
    total: 0,
    pageNum: 1,
    pageSize: 10
})

// 角色数据
const rolesData = ref([])

// 权限数据
const permissionsData = ref([])

// 获取角色
const getRoles = async () => {
    tableLoad.value = true
    try {
        const res = await axios.get("/api/basic/enterprise/roleByPage", {
            params: {
                pageNum: pageInfo.pageNum,
                pageSize: pageInfo.pageSize,
                ...searchForm
            }
        })
        if (res.data.code === 5200) {
            pageInfo.pageNum = res.data.pageInfo.pageNum
            pageInfo.total = res.data.pageInfo.total
            rolesData.value = res.data.pageInfo.list
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }

}

// 获取主要的权限
const getPermissions = async () => {
    try {
        const res = await axios.get('/api/basic/auth/permissionByPrimaryType')
        if (res.data.code === 5200) {
            permissionsData.value = res.data.permissions
        } else {
            ElMessage.error('权限获取失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 根据角色id获取权限
const getPermissionsByRoleId = async () => {
    try {
        const res = await axios.get('/api/basic/auth/getPermissionIdByRoleId', { params: { roleId: currentRoleId.value } })
        if (res.data.code === 5200) {
            permissionIds.value = res.data.permissionIdsList
        } else {
            ElMessage.error('权限获取失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

const handleCheck = (checked) => {
    searchForm.status = checked ? null : 1
    getRoles()
}

// 对话框
const openAddDialog = () => {
    form.value = { roleName: '' }
    dialogFormVisible.value = true
}

const openPermissionDialog = async (roleId) => {
    permissionIds.value = []
    currentRoleId.value = roleId
    permissionDialogFormVisible.value = true
    await getPermissionsByRoleId()
    await getPermissions()
    
}

const updateRole = async (id) => {
    dialogType.value = 'edit'
    const res = await axios.get('/api/basic/enterprise/roleById', { params: { id } })

    if (res.data.code === 5200) {
        form.value = res.data.role
        dialogFormVisible.value = true
    } else {
        ElMessage.error('获取数据失败')
    }
}
const searchRole = () => {
    pageInfo.pageNum = 1
    getRoles()
}

const submitRole = async () => {

    try {

        const url = dialogType.value === 'add' ? '/api/basic/enterprise/addRole' : '/api/basic/enterprise/updateRole'

        const res = await axios.post(url, form.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            dialogFormVisible.value = false
            await getRoles()
        } else {
            ElMessage.error(res.data.msg || '操作失败')
        }
    } catch (error) {
        ElMessage.error('请求失败')
    }
}

const submitPermissions = async () => {
    try {

        const rolePermission = {
            roleId: currentRoleId.value,
            permissionIds: permissionIds.value
        }
        const res = await axios.post('/api/basic/enterprise/insertRolePermissions', rolePermission)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            permissionDialogFormVisible.value = false
        } else {
            ElMessage.error(res.data.msg)
        }

    } catch (error) {
        ElMessage.error('请求失败')
    }
}

const handleSizeChange = async (val) => {
    pageInfo.pageSize = val
    pageInfo.pageNum = 1
    await getRoles()
}

const handleCurrentChange = async (val) => {
    pageInfo.pageNum = val
    await getRoles()
}

// 选中的对象
const selections = ref([])

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))

// 多选框变化
const handleSelection = (selection) => {
    selections.value = selection
}

// 切换状态
const handleStatus = async (row) => {
    tableLoad.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post("/api/basic/enterprise/updateRoleStatus", null, { params: { id: row.id, status: originalStatus === 1 ? 0 : 1 } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getRoles()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/enterprise/batchUpdateRoleStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getRoles()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除
const deleteRole = async (id) => {

    try {
        await ElMessageBox.confirm('此操作将永久删除该类别, 是否继续?', '删除类别', { type: 'warning' })
    } catch {
        return ElMessage.info('取消删除')
    }

    try {
        const res = await axios.post("/api/basic/enterprise/deleteRole", null, { params: { id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getRoles()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


// 批量删除
const batchDelete = async () => {

    try {
        await ElMessageBox.confirm('此操作将永久删除该类别, 是否继续?', '删除类别', { type: 'warning' })
    } catch {
        return ElMessage.info('取消删除')
    }

    try {
        const res = await axios.post("/api/basic/enterprise/batchDeleteRole", selectionIds.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getRoles()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}



// 刷新
const refresh = () => {
    // 重置表单
    searchForm.roleName = ''
    searchForm.status = 1

    // 重新查询（此时会显示默认启用列表）
    searchRole()
}

onMounted(() => {
    getRoles()
})

</script>

<style scoped>
/* 搜索表单 */

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    /* 控制元素之间的间距 */
    padding: 10px 0;
    overflow-x: auto;
    /* 如果内容超出屏幕宽度，允许水平滚动 */
}

/* 确保操作按钮组与左侧元素对齐 */
.search-right {
    margin-left: auto;
    /* 将右侧按钮组推到最右边 */
    display: flex;
    gap: 10px;
}

/* 复选框与链接样式 */
.search-container .el-checkbox {
    margin-left: auto;
    /* 自动边距将复选框推到中间 */
}

.search-container .el-link {
    font-size: 12px;
    color: #409eff;
}


.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>